package api;

import model.User;
import model.UserDao;
import view.HtmlGenerator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//用户登录
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //1.获取用户输入的用户名和密码,并进行简单校验
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if(name == null || "".equals(name)
        || password == null || "".equals(password)){
            //输入不合法
            String html = HtmlGenerator.getMessagePage("用户名或密码为空","login.html");
            resp.getWriter().write(html);
            return;
        }

        //2.看用户是否存在，且密码是否正确
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(name);
        if(user == null || !password.equals(user.getPassword())){
            String html = HtmlGenerator.getMessagePage("用户名或者密码错误","login.html");
            resp.getWriter().write(html);
            return;
        }

        //3.匹配成功就认为登录成功，建立一个session
        HttpSession httpSession = req.getSession(true);
        httpSession.setAttribute("user",user);
        //4.返回一个登录成功的页面
        String html = HtmlGenerator.getMessagePage("登陆成功","article");
        resp.getWriter().write(html);
    }
}
